import React, { useMemo } from 'react';
import ClassNames from 'classnames';
import useEmoji from '@/common/useEmoji';
import { viewSizeFormat } from '@/common/format';

const Emoji = ({ text, className: pClassName, formatter }) => {
  const { parse2Array } = useEmoji();

  return useMemo(() => parse2Array(text).map((row, index) => {
    const { tag, className, style, label, ...attrs } = formatter(row);

    return React.createElement(tag, {
      ...attrs,
      className: ClassNames(pClassName, className),
      style,
      key: index,
    }, label);
  }), [text]);
};

Emoji.defaultProps = {
  formatter: ({ label, value, type }) => {
    const style = {};
    const viewSize = viewSizeFormat(36);
    if (type === 'image') {
      style.display = 'inline-block';
      style.width = `${viewSize}px`;
      style.height = `${viewSize}px`;
      style.background = `url(${value}) no-repeat center`;
      style.backgroundSize = '100% auto';
      style.textIndent = '-9999999px';
    }
    return { tag: 'span', label, style };
  },
};

export default Emoji;
